﻿#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>

class Server
{
public:
    //构造函数
    Server(std::string ip, uint16_t port)
        :_sockfd(-1)
        , _ip(ip)
        , _port(port)
    {}


    //初始化
    bool init()
    {
        //创建套接字
        int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (socket_fd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return false;
        }
        std::cout << "socket succes" << std::endl;

        _sockfd = socket_fd;

        //绑定
        struct sockaddr_in local;
        //清零
        memset(&local, '\0', sizeof(local));
        //协议家族
        local.sin_family = AF_INET;
        //端口号
        local.sin_port = htons(_port);
        //IP
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        //绑定
        if (bind(_sockfd, (struct sockaddr*)&local, sizeof(struct sockaddr_in)) < 0)
        {
            //绑定失败
            std::cerr << "bind error" << std::endl;
            return false;
        }
        std::cout << "bind success" << std::endl;
        return true;
    }



    void start()
    {
        char buffer[1024];
        while (1)
        {
            //信息发送方信息
            struct sockaddr_in sendfrom;
            socklen_t len = sizeof(struct sockaddr_in);
            ssize_t size = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&sendfrom, &len);
            if (size > 0)
            {
                buffer[size] = '\0';
                int port = ntohs(sendfrom.sin_port);
                std::string ip = inet_ntoa(sendfrom.sin_addr);
                std::cout << ip << ":" << port << "# " << buffer << std::endl;
            }
            else
            {
                std::cerr << "recvfrom error" << std::endl;
            }
        }
    }

    //析构函数
    ~Server()
    {
        //关闭文件描述符表
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

private:
    //文件描述符
    int _sockfd;
    //ip地址
    std::string _ip;
    //端口号
    uint16_t _port;
};